package online.heycm.platform.lock;

import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.util.StringUtils;

/**
 * Redisson单机模式自动装配
 *
 * @author heycm
 * @since 2023/1/27 16:31
 */
@Slf4j
// @Configuration 通过@EnableDistributedLock加载
@ConditionalOnProperty(value = "spring.data.redis.host")
@EnableConfigurationProperties(RedisSingleProperties.class)
public class RedisSingleLockAutoConfiguration {

    private static final String REDIS_PREFIX = "redis://";

    @Autowired
    private RedisSingleProperties properties;

    public RedisSingleLockAutoConfiguration() {
        log.info("RedisSingleLockAutoConfiguration init...");
    }

    @Bean
    public RedissonClient redissonClient() {
        String address = String.format("%s%s:%s", REDIS_PREFIX, properties.getHost(), properties.getPort());
        Config config = new Config();
        config.useSingleServer()
                .setAddress(address)
                .setDatabase(properties.getDatabase())
                .setUsername(StringUtils.hasText(properties.getUsername()) ? properties.getUsername() : null)
                .setPassword(StringUtils.hasText(properties.getPassword()) ? properties.getPassword() : null);
        return Redisson.create(config);
    }

    @Bean
    public RedisLock redisLock(RedissonClient redissonClient) {
        return new RedisLockImpl(redissonClient);
    }

}
